#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QCloseEvent>
#include <QTime>
#include <QStyle>
#include <QPainter>
#include <QDir>
#include <QStandardPaths>
#include <QSettings>
#include <QDebug>

#include "config.h"

static void appAutoRun(bool bAutoRun)
{
#ifdef Q_OS_WIN32
    QString application_name = QApplication::applicationName();
    QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    if(bAutoRun){
        QString application_path = QApplication::applicationFilePath();
        settings.setValue(application_name, application_path.replace("/", "\\"));
    }else{
        settings.remove(application_name);
    }
#endif
}

static bool appIsAutoRun()
{
#ifdef Q_OS_WIN32
    QString application_name = QApplication::applicationName();
    QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    return settings.contains(application_name);
#endif
    return false;
}

QString formatTimeFromMilliseconds(qint64 milliseconds) {
    QTime time = QTime::fromMSecsSinceStartOfDay(milliseconds);
    int hours = time.hour();
    int minutes = time.minute();
    int seconds = time.second();
    // int msecs = time.msec();

    QString timeString;

    if (hours > 0) {
        timeString = QString("%1小时%2分钟%3秒")
                         .arg(hours)
                         .arg(minutes)
                         .arg(seconds);
    } else if (minutes > 0) {
        timeString = QString("%1分钟%2秒")
                         .arg(minutes)
                         .arg(seconds);
    } else {
        timeString = QString("%1秒")
                         .arg(seconds);
    }

    return timeString;
}



static QIcon qiconFromSvg(QString svg_path, QString color)
{
    QPixmap img(svg_path);
    QPainter qp(&img);
    qp.setCompositionMode(QPainter::CompositionMode_SourceIn);
    qp.fillRect( img.rect(), QColor(color) );
    qp.end();
    return QIcon(img);
}



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    loadConfig();
    ui->checkAutoRun->setChecked(appIsAutoRun());

    setWindowIcon(QIcon(":/resource/tips.ico"));
    QString svg_path = ":/resource/tips_icon.svg";
    m_normalIcon = qiconFromSvg(svg_path, "#00BFFF");//#4F91F9
    m_grayIcon = qiconFromSvg(svg_path, "gray");//#4F91F9
    m_redIcon = qiconFromSvg(svg_path, "transparent");//#d81e06
    m_greenIcon = qiconFromSvg(svg_path, "#FFD700");//#1afa29

    m_sysTrayIcon = new QSystemTrayIcon(this);
    m_sysTrayIcon->setToolTip("Tip it, now!");
    m_sysTrayIcon->setIcon(m_grayIcon);
    // 增加托盘菜单
    QMenu *menu = new QMenu();
    QAction *options = new QAction("选项");
    QAction *start = new QAction("开始");
    QAction *end = new QAction("结束");
    QAction *quit = new QAction("退出");

    menu->addAction(options);
    menu->addSeparator();
    menu->addAction(start);
    menu->addAction(end);
    menu->addSeparator();
    menu->addAction(quit);
    m_sysTrayIcon->setContextMenu(menu);

    connect(options, &QAction::triggered, this, [=]() {
        show();
    });

    connect(start, &QAction::triggered, this, [=]() {
        if(!m_timer->isActive())
            m_timer->start();
        start->setEnabled(false);
        end->setEnabled(true);
        m_sysTrayIcon->setIcon(m_normalIcon);
    });

    connect(end, &QAction::triggered, this, [=]() {
        if(m_timer->isActive())
            m_timer->stop();
        start->setEnabled(true);
        end->setEnabled(false);
        m_sysTrayIcon->setToolTip("Tip it, now!");
        m_sysTrayIcon->setIcon(m_grayIcon);
    });

    connect(quit, &QAction::triggered, this, [=]() {
        if(m_timer->isActive())
            m_timer->stop();
        qApp->quit();
    });

    // 关联拖盘事件
    connect(m_sysTrayIcon, &QSystemTrayIcon::activated, this, &MainWindow::onActivated);
    connect(m_sysTrayIcon, &QSystemTrayIcon::messageClicked, this, [=]() {
        emit start->trigger();
    });

    m_sysTrayIcon->show();

    m_timer = new QTimer(this);
    m_timer->setInterval(ui->intervalMinutes->value()*60*1000);
    // ui->intervalMinutes->setValue(1);
    // m_timer->setInterval(ui->intervalMinutes->value()*5000);
    connect(m_timer, &QTimer::timeout, this, [=]() {
        m_sysTrayIcon->showMessage(ui->timedTip->text(), QString("计时%1分钟已到").arg(ui->intervalMinutes->value()), QSystemTrayIcon::MessageIcon::Information, 5000);
        QApplication::alert(this);
        m_blink = true;
    });

    m_updateTimer = new QTimer(this);
    m_updateTimer->setInterval(ui->flickInterval->value());
    connect(m_updateTimer, &QTimer::timeout, this, [=]() {
        if(m_timer->isActive()) {
            m_sysTrayIcon->setToolTip(QString("时间剩余：") + formatTimeFromMilliseconds(m_timer->remainingTime()));
            if(m_blink) {
                m_blinkCount++;
                if(m_blinkCount % 2 == 0)
                    m_sysTrayIcon->setIcon(m_greenIcon);
                else
                    m_sysTrayIcon->setIcon(m_redIcon);
            }
        }

    });
    m_updateTimer->start();
    emit end->triggered();
    m_sysTrayIcon->showMessage(ui->startTip->text(), QString("定时提醒已开，点击即可开始计时"), QSystemTrayIcon::MessageIcon::Information, 500);
}

MainWindow::~MainWindow()
{
    saveConfig();
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    hide();
    e->ignore();
}

void MainWindow::onActivated(QSystemTrayIcon::ActivationReason action)
{
    qDebug()<<action;
    if(action==QSystemTrayIcon::ActivationReason::Unknown) {
        qDebug()<<"未知点击";
    }
    else if(action==QSystemTrayIcon::ActivationReason::Trigger) {
        qDebug()<<"鼠标单击";
        if(m_blink)
            m_sysTrayIcon->setIcon(m_normalIcon);
        m_blink = false;
        m_blinkCount = 0;
    }
    else if(action==QSystemTrayIcon::ActivationReason::DoubleClick) {
        qDebug()<<"鼠标双击";
        show();
    }
    else if(action==QSystemTrayIcon::ActivationReason::MiddleClick) {
        qDebug()<<"鼠标中间单击";
    }else{
        return;
    }
}


// void MainWindow::on_intervalMinutes_valueChanged(int mins)
// {
//     m_timer->setInterval(mins*60*1000);
//     m_sysTrayIcon->showMessage(ui->changeTips->text(), QString("更改时间间隔为%1分钟%2")
//                                                    .arg(mins)
//                                                    .arg(m_timer->isActive() ? "，将重新开始计时" : ""),
//                                QSystemTrayIcon::MessageIcon::Information, 500);
//     if(m_timer->isActive())
//         m_timer->start();
// }


// void MainWindow::on_flickInterval_valueChanged(int ms)
// {
//     m_updateTimer->setInterval(ms);
//     m_sysTrayIcon->showMessage(ui->changeTips->text(), QString("更改闪烁间隔为%1毫秒")
//                                                    .arg(ms),
//                                QSystemTrayIcon::MessageIcon::Information, 500);
//     m_updateTimer->start();
// }

void MainWindow::on_intervalMinutes_editingFinished()
{
    int mins = ui->intervalMinutes->value();
    if(qCfg.intervalMinutes == mins)
        return;
    qCfg.intervalMinutes = mins;
    m_timer->setInterval(mins*60*1000);
    m_sysTrayIcon->showMessage(ui->changeTips->text(), QString("更改时间间隔为%1分钟%2")
                                                           .arg(mins)
                                                           .arg(m_timer->isActive() ? "，将重新开始计时" : ""),
                               QSystemTrayIcon::MessageIcon::Information, 500);
    if(m_timer->isActive())
        m_timer->start();
}


void MainWindow::on_flickInterval_editingFinished()
{
    int ms = ui->flickInterval->value();
    if(qCfg.flickInterval == ms)
        return;
    qCfg.flickInterval = ms;
    m_updateTimer->setInterval(ms);
    m_sysTrayIcon->showMessage(ui->changeTips->text(), QString("更改闪烁间隔为%1毫秒")
                                                           .arg(ms),
                               QSystemTrayIcon::MessageIcon::Information, 500);
    m_updateTimer->start();
}

void MainWindow::loadConfig()
{
    ui->intervalMinutes->setValue(qCfg.intervalMinutes);
    ui->flickInterval->setValue(qCfg.flickInterval);
    ui->startTip->setText(qCfg.startTip);
    ui->timedTip->setText(qCfg.timedTip);
    ui->changeTips->setText(qCfg.changeTips);
}

void MainWindow::saveConfig()
{
    qCfg.intervalMinutes = ui->intervalMinutes->value();
    qCfg.flickInterval = ui->flickInterval->value();
    qCfg.startTip = ui->startTip->text();
    qCfg.timedTip = ui->timedTip->text();
    qCfg.changeTips = ui->changeTips->text();
}

void MainWindow::on_checkAutoRun_clicked(bool checked)
{
    appAutoRun(checked);
}

